<?php


namespace app\common\model;


use app\common\model\AdminLoginLog as adminLoginLogModel;
use thans\jwt\facade\JWTAuth;
use think\facade\Cookie;
use think\Model;
use function EasyWeChat\Kernel\Support\get_client_ip;

class Admin extends Model {

    const SUPER_ID = 1;
    const TYPE_SUPER_ID = 1;
    protected $pk = 'admin_id';
    protected $autoWriteTimestamp = true;


    public function getLoginTimeAttr($value){
        return format_intdate($value);
    }

    //设置密码
    public function setAdminPasswordAttr($value){
        return password_encode($value);
    }

    public function setReginTimeAttr($value){
        return time();
    }

    //常规方法

    //添加一个管理员
    public function addAdmin($data){
        return $this->save($data);
    }

    public function toLogin($data){
        if (!isset($data['username']) || !isset($data['password'])) {
            return error_code(11031);
        }
        $admin_password = $this->where('admin_name',$data['username'])->field('admin_password')->findOrEmpty();
        if($admin_password->isEmpty()){
            return error_code(11032);
        }
        //验证密码是否正确
        if(password_encode($data['password']) != $admin_password['admin_password']){
            return error_code(11033);
        }
        //这里其实已经登录成功了
        $admin_info = $this->where('admin_name',$data['username'])->findOrEmpty();
        //添加登录日志
        $adminLoginLogModel = new adminLoginLogModel();
        $adminLoginLogModel->save([
            'admin_id'=>$admin_info['admin_id'],
            'name'=>$admin_info['name'],
            'ip'=>get_client_ip(),
            'created_at'=>time()
        ]);
        //获取token
        $token = JWTAuth::builder(['admin_id'=>$admin_info['admin_id']]);
        Cookie::set('token',$token);
        Cookie::set('admin_id',$admin_info['admin_id']);
        $res = [
            'status'=>true,
            'data'=>redirect_url(),
        ];
        return $res;
    }

    public function userLoginLogList(){
        $adminLoginModel = new adminLoginLogModel();
        return json(gsuc($adminLoginModel->order('id','desc')->paginate(10)));
    }


    public function changePwd($admin_id, $oldPassword, $newPassword)
    {
        $result = [
            'status' => false,
            'data'   => '',
            'msg'    => ''
        ];
        $info   = $this->where(['admin_id' => $admin_id])->find();
        if (!$info) {

            return error_code(11032);
        }
        if ($oldPassword == $newPassword) {

            return error_code(11044);
        }
        if ($info['admin_password'] != password_encode($oldPassword)) {
            return error_code(11045);
        }

        $re = $this->where('admin_id',$info['admin_id'])->save(['admin_password' => password_encode($newPassword)]);
        if ($re) {
            $result['status'] = true;
            $result['msg']    = "修改成功";
        } else {
            return error_code(10024);
        }
        return $result;
    }

    /**
     * 注册添加用户
     * @param $data //新建用户的数据数组
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function toAdd($data)
    {
        $result = array(
            'status' => false,
            'data'   => '',
            'msg'    => ''
        );


        //判断是新增还是修改
        if (isset($data['id'])) {
            $manageInfo = $this->where(['admin_id' => $data['id']])->find();
            if (!$manageInfo) {
                return error_code(11010);
            }

            if (isset($data['admin_password']) && !empty($data['admin_password'])) {
                if (strlen($data['admin_password']) <= 5 || strlen($data['admin_password']) > 16) {
                    return error_code(11009);
                } else {
                    $data['admin_password'] = password_encode($data['admin_password']);
                }
            } else {
                unset($data['admin_password']);
            }

            unset($data['admin_name']);       //不允许修改用户名
            //更新数据库
            $this->where('admin_id',$data['id'])->strict(false)->save($data);
//            $this->allowField(true)->where('admin_id',$data['id'])->save($data);
        } else {
            //判断用户名是否重复
            $manageInfo = $this->where(['admin_name' => $data['admin_name']])->find();
            if ($manageInfo) {
                return error_code(11011);
            }
            $data['created_at'] = TIMESTAMP;
            $data['updated_at'] = TIMESTAMP;

            if (!isset($data['admin_password'][5]) || isset($data['admin_password'][16])) {
                return error_code(11009);
            }
            $data['admin_password'] = password_encode($data['admin_password']);
            //插入数据库
            $admin_id = $this->strict(false)->insertGetId($data);
            $data['id'] = $admin_id;
        }
        //设置角色
        $roleRelModel = new AdminRoleRel();
        //清空所有的旧角色
        $roleRelModel->where(['admin_id' => $data['id']])->delete();

        if (isset($data['role_id'])) {
            $data1 = [];
            foreach ($data['role_id'] as $k => $v) {
                $row['admin_id'] = $data['id'];
                $row['role_id']   = $k;
                $data1[]          = $row;
            }
            $roleRelModel->saveAll($data1);
        }
        $result['status'] = true;
        return $result;
    }

}